//
//  NetworkAPI.swift
//  Motion
//
//  Created by 悦月越悦 on 2021/4/6.
//

import Foundation

struct CourseTest:Decodable{
    var courseId: Int
    var courseName: String
}

class NetworkAPI{
    static func getInfo(completion: @escaping (Result<CourseTest, Error>) -> Void) {
        NetworkManager.shared.requestGet(path: "getInfo", parameters: nil) { result in
            switch result {
                case let .success(data):
                    let parseResult: Result<CourseTest, Error> = self.parseData(data)
                    completion(parseResult)
                case let .failure(error):
                    completion(.failure(error))
            }
        }
    }
    
    private static func parseData<T: Decodable>(_ data: Data) -> Result<T, Error> {
        
        guard let decodedData = try? JSONDecoder().decode(ResponseData<T>.self, from: data) else {
            let error = NSError(domain: "NetworkAPIError", code: 0, userInfo: [NSLocalizedDescriptionKey: "Can not parse data"])
            return .failure(error)
        }
        
        if(decodedData.status == .failed){
            let error = NSError(domain: "NetworkAPIError", code: 0, userInfo: [NSLocalizedDescriptionKey: "服务器发生了🙅‍♂️"])
            return .failure(error)
        }
        
        return .success(decodedData.data)
    }
}
